//Index JavaScript

function UiList(settings){
	var defaultTableConfig = {
			url: null,
			idfield: 'id',
			toolbar: 'toolbar',
			cache: false,	//禁用 AJAX 数据缓存
			striped: true,	//表格显示条纹
			pagination: true,//显示分页组件
			pageList: [15, 20, 50],
			pageSize: 15,
			pageNumber: 1,
			sidePagination: 'server',
			queryParams: null,//由组件赋值，额外参数使用p.tableParams参数提供
			columns: null
		};
	var defaultOptions = {
			path: window.context_path || '',
			treeId: 'jstree',
			treeUrl: null,
			treeWidth: 340,
			treeExpandOnSelect: true,
			treeConfig: {
				core:{
					data: {
						url: null,
						data: function (node) {
							var pparam = {pid : node.id};
							if(node.original){
								pparam.pdatatype = node.original.type;
							}
							pparam.r = Math.random();
							return pparam;
						}
					},
					multiple: false
				}
			},
			tableId: 'dataTable',
			tableConfig: {
				url: null,
				idfield: 'id',
				toolbar: 'toolbar'
			},
			tableParams: null,//附加参数方法function(){retunr {search: search};}
			multiTableSupport: false,//开启多类型表格支持
			multiTableConfig: null,//表格配置{type1:tableConfig1, type2:tableConfig2},type为左侧树节点的type属性
			rememberTreeSelect: true,
			onTreeSelect: null, //选中树节点时的操作，取代默认行为：function(selectedTreeNode, oldSelectedTreeNode)
			onResize: null //页面大小变化时调用：function(bodyDivWidth)
		};
	var g = this, p = g.options = jQuery.extend(true, {}, defaultOptions, settings);
	
	g._init=function(){
		//导航树
		if(p.treeId && p.treeUrl){
			g.jstree = $('#'+p.treeId);
			g.setTreeWidth();
			if(p.treeUrl){
				p.treeConfig.core.data.url = p.treeUrl;
			}
			g.jstree.data('jstree', false).empty();
			g.jstree.jstree(p.treeConfig).on('select_node.jstree', function (event, data){
				if(p.rememberTreeSelect){
					var nodePath=[data.node.original.id], nodeParents=data.node.parents;
					for(var i=0,n=nodeParents.length-1;i<n;i++){
						nodePath.push(nodeParents[i]);
					}
					nodePath.reverse();
					$.cookie("UiListNodePath", nodePath.join(";"), {path:'/'});
				}
				if(!p.multiTableSupport){
					g.oldSelectedTreeNode = g.selectedTreeNode;
					g.selectedTreeNode = data.node.original;
					if(p.treeExpandOnSelect){
						g.jstree.jstree("open_node", data.node);
					}
					if(p.onTreeSelect){
						p.onTreeSelect.call(g, g.selectedTreeNode, g.oldSelectedTreeNode);
					}else{
						g.loadTable(p.tableConfig);
						g.dynamicButton('tree');
					}
				}else{
					if(p.treeExpandOnSelect){
						g.jstree.jstree("open_node", data.node);
					}
					g.oldSelectedTreeNode = g.selectedTreeNode;
					if(p.onTreeSelect){
						g.selectedTreeNode = data.node.original;
						p.onTreeSelect.call(g, g.selectedTreeNode, g.oldSelectedTreeNode);
					}else{
						var nodeData = data.node.original;
						if(!g.selectedTreeNode || g.selectedTreeNode.type != nodeData.type){
							g.selectedTreeNode = nodeData;
							$('.uilist-toolbar').hide();
							$('.uilist-toolbar-'+nodeData.type).show();
							$('.uilist-search').hide();
							$('.uilist-search-'+nodeData.type).show();
							g.createTable(p.multiTableConfig[nodeData.type]);
						}else{
							g.selectedTreeNode = nodeData;
							g.loadTable(p.multiTableConfig[nodeData.type]);
						}
					}
					
				}
		    }).on('loaded.jstree', function(e, data){
		    	var _node;
		    	if(p.rememberTreeSelect){
		    		var nodePath=$.cookie("UiListNodePath");
			    	if(nodePath){
			    		g._nodePath = nodePath.split(';');
			    		_node = data.instance.get_node(g._nodePath[0]);
			    	}
		    	}
		    	if(!_node){
		    		g._nodePath = null;
		    		var tree = data.instance;
			    	if(e.target.firstChild.firstChild){
			    		var obj = tree.get_node(e.target.firstChild.firstChild.lastChild);
			    		tree.select_node(obj);
			    	}
		    	}
		    }).on('load_node.jstree', function(e, data){
		    	var tree = data.instance, pnode = data.node, index = pnode.parents.length;
		    	if(g._nodePath){
		    		var _node = tree.get_node(g._nodePath[index]);
		    		if(index == g._nodePath.length - 1 || !_node.original.state.hasChildren){
		    			if(_node){
		    				tree.select_node(_node);
		    			}
		    			g._nodePath = null;
		    		}else{
		    			var _node = tree.get_node(g._nodePath[index]);
		    			if(_node){
		    				tree.open_node(_node);
		    			}else{
		    				tree.select_node(pnode);
			    			g._nodePath = null;
			    		}
		    		}
		    	}
			});
		}else{
			g.loadTable(p.tableConfig);
		}
		
		$(window).resize(function(){
			g.resize();
		});
		g.resize();
	};
	
	g.setTreeWidth=function(){
		if(!g.jstree || !p.treeWidth){
			return;
		}
		var rowDiv = g.rowDiv = g.jstree.closest('.row');
		var treeDiv = g.treeDiv = rowDiv.children('div:eq(0)');
		var bodyDiv = g.bodyDiv = rowDiv.children('div:eq(1)');
		treeDiv.css({width: p.treeWidth+'px'});
		bodyDiv.css({width:($(window).width() - p.treeWidth - 40)+'px'});
		var bodyMinWidth = parseInt(bodyDiv.css('minWidth'));
		if(bodyMinWidth){
			rowDiv.css({minWidth:(p.treeWidth + bodyMinWidth + 10)+'px'});
		}
	};
	
	g.resize=function(){
		if(g.jstree){
			var con = g.jstree.parent().css({"maxHeight": ($(window).height()-100)+"px", "overflow":"auto"});
		}
		if(g.bodyDiv){
			g.bodyDiv.css({width:($(window).width() - p.treeWidth - 40)+'px'});
			if(p.onResize){
				p.onResize.call(g, g.bodyDiv.width());
			}
		}else{
			if(p.onResize){
				p.onResize.call(g, $(window).width());
			}
		}
	};
	
	g.dynamicButton=function(type){
		if(type=='tree' && g.selectedTreeNode && g.selectedTreeNode.type){
			$("#"+g.tableConfig.toolbar+" button").each(function(){
				var btn=$(this), hide = btn.attr("uilist-hide");
				if(hide){
					var ishide=false, arr = hide.split("|");
					for(var i=0; i<arr.length; i++){
						var itm = arr[i];
						if(itm.indexOf('expr:') == 0){
							itm = itm.substring(5);
							if(itm.indexOf('!=') != -1){
								var a2 = itm.split("!=");
								if((g.selectedTreeNode[a2[0]]+'') != a2[1]){
									ishide = true;
									break;
								}
							}else if(itm.indexOf('==') != -1){
								var a2 = itm.split("==");
								if((g.selectedTreeNode[a2[0]]+'') == a2[1]){
									ishide = true;
									break;
								}
							}
						}else{
							if(itm == g.selectedTreeNode.type){
								ishide = true;
								break;
							}
						}
					}
					if(ishide){
						btn.hide();
					}else{
						btn.show();
					}
				}
			});
		}
		if(type=='table'){
			var num = g.table.bootstrapTable('getSelections').length, toolbar=$("#"+g.tableConfig.toolbar);
			if(num==0){
				 $('.single,.multi', toolbar).prop("disabled", true);
			}
			else if(num>1){
				$('.single', toolbar).prop("disabled", true);
				$('.multi', toolbar).prop("disabled", false);
			}
			else{//num==1
				$('.single,.multi', toolbar).prop("disabled", false);
			}
		}
		
	};
	
	g.refreshTree=function(all){
		if(g.jstree){
			if(!all && g.selectedTreeNode){
				g.jstree.jstree("refresh_node", g.selectedTreeNode);
			}else{
				g.jstree.jstree("refresh");
			}
		}
	};
	
	g.loadTable=function(tableConfig){
		if(g.table){
			g.table.bootstrapTable('refresh');
		}else{
			g.createTable(tableConfig);
		}
	};
	
	g.createTable = function(tableConfig){
		if(!tableConfig){
			return;
		}
		g.tableConfig = jQuery.extend(true, {}, defaultTableConfig, tableConfig);
		g.tableConfig.queryParams = function(params){
			var params = {
				page: parseInt(params.offset / params.limit) + 1,
				pagesize: params.limit,
				sortname: params.sort || '',
				sortorder: params.order
	          };
			if(g.selectedTreeNode){
				params.leftdata = g.selectedTreeNode.id;
				if(g.selectedTreeNode.field){
					params[g.selectedTreeNode.field] = g.selectedTreeNode.id;
				}
				if(g.selectedTreeNode.type){
					params.datatype = g.selectedTreeNode.type;
				}
			}
			if(p.tableParams){
				var tparams = p.tableParams.call(g);
				if(tparams){
					jQuery.extend(params, tparams);
				}
			}
			return params;
		};
		
		g.tableConfig.onCheck=function(row){
			g.dynamicButton('table');
		};
		g.tableConfig.onUncheck=function(row){
			g.dynamicButton('table');
		};
		g.tableConfig.onCheckAll=function(rows){
			g.dynamicButton('table');
		};
		g.tableConfig.onUncheckAll=function(rows){
			g.dynamicButton('table');
		};
		g.tableConfig.onPostBody=function(){
			g.dynamicButton('table');
		};
		g.table = $("#"+p.tableId);
		g.table.bootstrapTable('destroy');
		g.table.empty();
		g.table.bootstrapTable(g.tableConfig);
	};
	
	//opt:{uiparam:true|false,refresh:all|table|tree,width:800,height:520,full:true|false}
	g.open = function(url, title, opt){
		opt = opt || {};
		g.refreshType = opt.refresh;
		if(opt.uiparam !== false && g.selectedTreeNode){
			if(url.indexOf('?')==-1){
				url += '?';
			}else{
				url += '&';
			}
			url += 'leftdata='+g.selectedTreeNode.id;
			if(g.selectedTreeNode.type){
				url += '&datatype='+g.selectedTreeNode.type;
			}
		}
		g.layerIndex = layer.open(jQuery.extend({
				type : 2,
				title : title,
				maxmin : true,
				shadeClose : false, // 点击遮罩关闭层
				area : [ (opt.width||800)+'px', (opt.height||520)+'px' ],
				content : url
			}, (opt.layer||{})));
		if(opt.full == true){
			layer.full(g.layerIndex);
		}
	};
	
	//opt:{uiparam:true|false,refresh:all|table|tree,useTableData:true|false}
	g.dialog = function(url, confirm, succeed, opt){
		opt = opt || {};
		g.refreshType = opt.refresh;
		if(opt.useTableData === false){
			layer.confirm(confirm || "确认该操作吗?", {
				btn : [ '确定', '取消' ]
			// 按钮
			}, function() {
				if(opt.uiparam !== false && g.selectedTreeNode){
					if(url.indexOf('?')==-1){
						url += '?';
					}else{
						url += '&';
					}
					url += 'leftdata='+g.selectedTreeNode.id;
					if(g.selectedTreeNode.type){
						url += '&datatype='+g.selectedTreeNode.type;
					}
				}
				$.ajax({
					type : 'POST',
					url : url,
					dataType : 'text',
					success : function(data) {
						if(!UiUtil.hasErrors(data)){
							layer.msg(succeed || "操作成功.", {icon: 1});
							g.refresh(true);
						}
					}
				});
			}, function() {});
		}else{
			var rows = g.table.bootstrapTable('getSelections');
			if (rows.length == 0) {
				layer.msg("至少选择一条数据");
				return;
			}
			layer.confirm(confirm || "确认该操作吗?", {
				btn : [ '确定', '取消' ]
			// 按钮
			}, function() {
				var ids = [], idfield = g.tableConfig.idfield;
				$.each(rows, function(i, row) {
					ids.push(idfield+'='+row[idfield]);
				});
				if(opt.uiparam !== false && g.selectedTreeNode){
					if(url.indexOf('?')==-1){
						url += '?';
					}else{
						url += '&';
					}
					url += 'leftdata='+g.selectedTreeNode.id;
					if(g.selectedTreeNode.type){
						url += '&datatype='+g.selectedTreeNode.type;
					}
				}
				$.ajax({
					type : 'POST',
					data : ids.join('&'),
					url : url,
					dataType : 'text',
					success : function(data) {
						if(!UiUtil.hasErrors(data)){
							layer.msg(succeed || "操作成功.", {icon: 1});
							g.refresh(true);
						}
					}
				});
			}, function() {});
		}
	};
	
	g.refresh = function(succeeded){
		layer.close(g.layerIndex);
		if(!succeeded){
			return;
		}
		if(!g.refreshType){
			g.loadTable();
		}else{
			if(g.refreshType=='all' || g.refreshType=='table' || g.refreshType===true){
				g.loadTable();
			}
			if(g.refreshType=='all' || g.refreshType=='left' || g.refreshType===true){
				g.refreshTree();
			}
		}
	};
	//初始化
	g._init();
}

UiList.render = function(settings){
	window._sysUiList = new UiList(settings);
	return window._sysUiList;
};
//opt:{uiparam:true|false,refresh:all|table|tree,width:800,height:520,full:true|false}
UiList.open = function(url, title, opt){
	if(window._sysUiList){
		window._sysUiList.open(url, title, opt);
	}
};
//opt:{uiparam:true|false,refresh:all|table|tree,useTableData:true|false}
UiList.dialog = function(url, confirm, succeed, opt){
	if(window._sysUiList){
		window._sysUiList.dialog(url, confirm, succeed, opt);
	}
};

UiList.selectPage=function(url, title, opt, callback){
	if(typeof opt == 'function'){
		callback = opt;
		opt = {};
	}
	opt.layer = {
		maxmin : false,
		btn: ['确定', '取消'],
		yes:function(index, layero){
			var iframeWin = $(layero).find('iframe')[0].contentWindow;
			callback.call(this, iframeWin);
			layer.close(index);
		},
		btn2: function(index){
			layer.close(index);
		}
	};
	if(window._sysUiList){
		window._sysUiList.open(url, title, opt);
	}
};

UiList.loadTable = function(){
	if(window._sysUiList){
		window._sysUiList.loadTable();
	}
};

UiList.getSelectedTreeNode = function(){
	if(window._sysUiList){
		return window._sysUiList.selectedTreeNode;
	}
	return null;
};
